package com.ibiaoke.customer.service;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.ibiaoke.common.base.Page;
import com.ibiaoke.common.configs.GlobalConfigs;
import com.ibiaoke.common.configs.GlobalConfigsKey;
import com.ibiaoke.common.configs.WeChatConfigs;
import com.ibiaoke.common.consts.CommonConsts;
import com.ibiaoke.common.consts.WeChatConsts;
import com.ibiaoke.common.exception.ServiceException;
import com.ibiaoke.common.spring.ExceptionAspect;
import com.ibiaoke.common.utils.AssertUtils;
import com.ibiaoke.common.utils.HttpUtil;
import com.ibiaoke.customer.dao.ThirdPartLoginDao;
import com.ibiaoke.customer.entity.Customer;
import com.ibiaoke.customer.entity.ThirdPartLogin;
import com.ibiaoke.customer.entity.ThirdPartLoginExample;
import com.ibiaoke.customer.entity.vo.CustomerVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Service("thirdPartyLoginService")
public class ThirdPartLoginServiceImpl implements ThirdPartLoginService {

    @Autowired
    private ThirdPartLoginDao thirdPartLoginDao;

    private static Logger logger = LoggerFactory.getLogger(ExceptionAspect.class);

    @Override
    public ThirdPartLogin getByUid(String uId) {
        if (StringUtils.isBlank(uId)) {
            return null;
        }
        ThirdPartLoginExample example = new ThirdPartLoginExample();
        example.createCriteria().andUIdEqualTo(uId);
        List<ThirdPartLogin> thirdPartyLogins = thirdPartLoginDao.selectByExample(example);
        return CollectionUtils.isEmpty(thirdPartyLogins) ? null : thirdPartyLogins.get(0);
    }

    @Override
    public ThirdPartLogin getByXid(String xId) {
        if (StringUtils.isBlank(xId)) {
            return null;
        }
        ThirdPartLoginExample example = new ThirdPartLoginExample();
        example.createCriteria().andXIdEqualTo(xId);
        List<ThirdPartLogin> thirdPartyLogins = thirdPartLoginDao.selectByExample(example);
        return CollectionUtils.isEmpty(thirdPartyLogins) ? null : thirdPartyLogins.get(0);
    }

    @Override
    public void bind(ThirdPartLogin thirdPartLogin,String accessToken) {
        ThirdPartLogin byUid = getByUid(thirdPartLogin.getuId());
        if (byUid != null) {
            throw new ServiceException("您的账号已绑定过手机号");
        }
        thirdPartLoginDao.insert(thirdPartLogin);
        updateHeadPicAndNickName(thirdPartLogin.getuId(),accessToken);
    }


    /**
     * 设置用户名和头像
     */
    @Override
    public int updateHeadPicAndNickName(String openId,String accessToken) {
        if (StringUtils.isBlank(openId)) {
            return 0;
        }
        JSONObject result = null;
        String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + WeChatConfigs.getAccessToken() + "&openid=" + openId + "&lang=zh_CN";
        String res = HttpUtil.httpClientGet(url);
        result = JSONObject.parseObject(res);

        if("0".equals(result.getString("subscribe"))){
            String url4 = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
            String res4 = HttpUtil.httpClientGet(url4);
            result = JSONObject.parseObject(res4);
        }

        String headImgUrl = result.getString("headimgurl");
        String nickName = result.getString("nickname");


        if (StringUtils.isEmpty(headImgUrl) && StringUtils.isEmpty(nickName)) {
            logger.error("获取用户微信信息失败,url:{},微信返回数据:{}", url, res);
            return 0;
        }
        return thirdPartLoginDao.updateByOpenId(openId, headImgUrl, nickName);
    }

    @Override
    public List<ThirdPartLogin> queryByUserIds(List<Integer> userIds) {
        if (CollectionUtils.isEmpty(userIds)) {
            return Lists.newArrayList();
        }
        ThirdPartLoginExample example = new ThirdPartLoginExample();
        example.createCriteria().andUserIdIn(userIds);
        return thirdPartLoginDao.selectByExample(example);
    }

    @Override
    public ThirdPartLogin getThiedPartLogin(String mobile) {
        ThirdPartLoginExample example = new ThirdPartLoginExample();
        example.createCriteria().andMobileEqualTo(mobile);
        return thirdPartLoginDao.selectByExample(example).get(0);
    }

    @Override
    public List<ThirdPartLogin> listThiedPartLogin(List<Integer> customerIds) {
        return thirdPartLoginDao.listThiedPartLogin(customerIds);
    }

    @Override
    public int editUserMobile(Customer customer, CustomerVO customerVO) {
        AssertUtils.notNull(customer.getCustomerId(),"用户Id不能为空");
        AssertUtils.notBlank(customerVO.getCustomerMobile(),"手机号码不能为空");
        AssertUtils.requireTrue(customer.getCustomerMobile() != customerVO.getCustomerMobile(),"新号码不能与旧号码相同");
        return thirdPartLoginDao.editUserMobile(customer.getCustomerId(),customerVO.getCustomerMobile());
    }

    @Override
    public ThirdPartLogin getInfo(Integer customerId) {
        AssertUtils.notNull(customerId,"用户Id不能为空");
        ThirdPartLoginExample example = new ThirdPartLoginExample();
        example.createCriteria().andUserIdEqualTo(customerId);
        return thirdPartLoginDao.getByExample(example);
    }
}
